<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Comment_mdl extends MY_Model {

    public function __construct(){
        parent::__construct();
        $this->table = 'comment';
    }

    public $_validation = [
        [
            'field' => 'title',
            'label' => '公告标题',
            'rules' => 'required|max_length[30]|is_unique[comment.title]',
            'errors' => [
                'required' => "%s不能为空",
                'max_length' => "%s长度不能大于30个字符",
                'is_unique' => "%s重复，已经存在该标题公告"
            ]
        ],
        [
            'field' => 'content',
            'label' => '公告内容',
            'rules' => 'required|max_length[250]',
            'errors' => [
                'required' => "%s不能为空",
                'max_length' => "%s长度不能大于255个字符",
            ]
        ]
    ];

    public function add($data){
        $tmp = [
            'status' => $data['status'] == 1 ? 1 : 2,
            'create_time' => $_SERVER['REQUEST_TIME'],
            'click' => 0,
            'user_id' => $_SESSION['user']['id'],
            'update_time' => $_SERVER['REQUEST_TIME']
        ];

        $res = $this->create(array_merge($data,$tmp));

        //将公告发送数据发送到每个用户
		$this->send_user(['id'=>$res,'title'=>$data['title']]);

        if($res === false){
            return FALSE;
        }
        //设置只能有一个公告可以显示
        if($tmp['status'] == 1){
            $this->set_status($res);
        }
        return TRUE;
    }

    /**
     * 将公告数据发送到每个用户
     */
    public function send_user($data){
    	$this->load->model('news_mdl');
		$con = '<a href="'.site_url("comment/show?cid=".$data["id"]).'">'.$data['title'].'</a>';
		$this->news_mdl->send_user('a',$con,1);
    }
     

    /**
     * 设置只能显示一个公告
     */
    public function set_status($id){
        $this->db->where('id !=',$id);
        $this->db->set('status',2);
        $res = $this->update();
        return $res;
    }

    /**
     * 获取首页显示公告
     */
    public function get_comm_one(){
        $this->db->where('status',1);
        $this->db->select('id,title');
        return $this->get_one();
    }

    /**
     * 修改数据
     */
    public function edit($data){
        $data['update_time'] = $_SERVER['REQUEST_TIME'];
        $cid = $data['cid'];
        $this->db->where('id',$cid);
        unset($data['cid']);
        $res = $this->update($data);
        if($res === false){
            return false;
        }

        if($data['status'] == 1){
            $this->set_status($cid);
        }
        return true;
    }


}

/* End of file Comment_mdl.php */
/* Location: ./application/models/Comment_mdl.php */